/*
 * Copyright (C) 2008-12  Bernhard Hobiger
 *
 * This file is part of HoDoKu.
 *
 * HoDoKu is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * HoDoKu is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with HoDoKu. If not, see <http://www.gnu.org/licenses/>.
 */

package sudoku;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ResourceBundle;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;

/**
 *
 * @author hobiwan
 */
public class SetGivensDialog extends javax.swing.JDialog {
    private static final long serialVersionUID = 1L;
    private boolean okPressed = false;
    private String givens = null;

    /** Creates new form SetGivensDialog
     * @param parent
     * @param modal  
     */
    public SetGivensDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        getRootPane().setDefaultButton(okButton);

        KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
        Action escapeAction = new AbstractAction() {
            private static final long serialVersionUID = 1L;
            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible( false );
            }
        };
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke, "ESCAPE");
        getRootPane().getActionMap().put("ESCAPE", escapeAction);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        givensTextArea = new javax.swing.JTextArea();
        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("intl/SetGivensDialog"); // NOI18N
        setTitle(bundle.getString("SetGivensDialog.title")); // NOI18N

        jLabel1.setText(bundle.getString("SetGivensDialog.jLabel1.text")); // NOI18N

        givensTextArea.setColumns(20);
        givensTextArea.setRows(5);
        jScrollPane1.setViewportView(givensTextArea);

        okButton.setMnemonic(java.util.ResourceBundle.getBundle("intl/SetGivensDialog").getString("SetGivensDialog.okButton.mnemonic").charAt(0));
        okButton.setText(bundle.getString("SetGivensDialog.okButton.text")); // NOI18N
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        cancelButton.setMnemonic(java.util.ResourceBundle.getBundle("intl/SetGivensDialog").getString("SetGivensDialog.cancelButton.mnemonics").charAt(0));
        cancelButton.setText(bundle.getString("SetGivensDialog.cancelButton.text")); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 404, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(okButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, okButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 319, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(okButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        okPressed = false;
        setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        String text = givensTextArea.getText();
        String lineEnd = null;
        if (text.contains("\r\n")) {
            lineEnd = "\r\n";
        } else if (text.contains("\r")) {
            lineEnd = "\r";
        } else if (text.contains("\n")) {
            lineEnd = "\n";
        }
        String[] lines = text.split(text);
        if (lineEnd != null) {
            lines = text.split(lineEnd);
        } else {
            lines = new String[1];
            lines[0] = text;
        }
        StringBuilder output = new StringBuilder();
        for (int i = 0; i < lines.length; i++) {
            if (lines[i] != null) {
                // remove border lines (all lines that contain "---")
                lines[i] = lines[i].trim();
                if (lines[i].contains("---")) {
                    for (int j = i; j < lines.length - 1; j++) {
                        lines[j] = lines[j + 1];
                    }
                    lines[lines.length - 1] = null;
                }
            }
            if (lines[i] != null) {
                // remove all characters except digits and '.'
                StringBuffer tmp = new StringBuffer(lines[i].trim());
                for (int j = 0; j < tmp.length(); j++) {
                    char ch = tmp.charAt(j);
                    if (! Character.isDigit(ch) && ch != '.') {
                        tmp.deleteCharAt(j);
                        j--;
                    }
                }
                output.append(tmp);
            }
        }
        givens = output.toString();
//        System.out.println("givens <" + givens + ">");
        if (givens.length() != 81) {
            JOptionPane.showMessageDialog(rootPane, 
                    ResourceBundle.getBundle("intl/SetGivensDialog").getString("SetGivensDialog.error.message"),
                    ResourceBundle.getBundle("intl/SetGivensDialog").getString("SetGivensDialog.error.title"),
                    JOptionPane.ERROR_MESSAGE);
            givens = null;
            return;
        }
        okPressed = true;
        setVisible(false);
    }//GEN-LAST:event_okButtonActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                SetGivensDialog dialog = new SetGivensDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JTextArea givensTextArea;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton okButton;
    // End of variables declaration//GEN-END:variables

    /**
     * @return the okPressed
     */
    public boolean isOkPressed() {
        return okPressed;
    }

    /**
     * @return the givens
     */
    public String getGivens() {
        return givens;
    }

}
